package com.chinatelecom.ifree.business.configcenter.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chinatelecom.ifree.business.configcenter.ZkHelp;
import com.github.zkclient.IZkDataListener;

public class UamRedirectHelper {
	private final static Logger logger = LoggerFactory.getLogger(UamRedirectHelper.class);
	private final static String redirectZkPath = "/ifree/uam/redirect";
	private final static String returnZkPath = "/ifree/uam/return";
	private String redirectUrl = null;
	private String returnUrl = null;
	private ZkHelp zkHelp = ZkHelp.getInstance();
	private static UamRedirectHelper instance = null;
	private static IZkDataListener listenerRedirect = null;
	private static IZkDataListener listenerReturn = null;

	private UamRedirectHelper() {
		// 登录UAM重定向定址
		listenerRedirect = new IZkDataListener() {
			@Override
			public void handleDataDeleted(String dataPath) throws Exception {
				logger.info("!!! rsVersion node data has been deleted !!!" + dataPath);
			}

			@Override
			public void handleDataChange(String dataPath, byte[] data) throws Exception {
				logger.info("!!! rsVersion node data has been changed !!!" + dataPath);
				String rtdata = null;
				if (data != null && data.length > 0) {
					rtdata = new String(data, "UTF-8");
					redirectUrl = rtdata;
				}
				logger.info("!!! rsVersion node data has been changed ok !!!" + rtdata);
			}
		};
		// 添加节点监控
		zkHelp.subscribeDataChanges(redirectZkPath, listenerRedirect);
		redirectUrl = new String(zkHelp.getValue(redirectZkPath));

		// 登录退出返回地址
		listenerReturn = new IZkDataListener() {
			@Override
			public void handleDataDeleted(String dataPath) throws Exception {
				logger.info("!!! rsVersion node data has been deleted !!!" + dataPath);
			}

			@Override
			public void handleDataChange(String dataPath, byte[] data) throws Exception {
				logger.info("!!! rsVersion node data has been changed !!!" + dataPath);
				String rtdata = null;
				if (data != null && data.length > 0) {
					rtdata = new String(data, "UTF-8");
					returnUrl = rtdata;
				}
				logger.info("!!! rsVersion node data has been changed ok !!!" + rtdata);
			}
		};
		// 添加节点监控
		zkHelp.subscribeDataChanges(returnZkPath, listenerReturn);
		returnUrl = new String(zkHelp.getValue(returnZkPath));
		if (logger.isInfoEnabled())
			logger.info("===================init UamRedirectHelper ok================");
	}

	public static UamRedirectHelper getInstance() {
		if (instance == null) {
			synchronized (UamRedirectHelper.class) {
				instance = new UamRedirectHelper();
			}
		}
		return instance;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}

	public String getReturnUrl() {
		return returnUrl;
	}

	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}
}
